package org.jeecg.modules.yusuannz.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.yusuannz.entity.CaiwuShangnianNz;
import org.jeecg.modules.yusuannz.service.ICaiwuShangnianNzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
* @Author: jeecg-boot
* @Date:   2020-06-15
* @Version: V1.0
*/
@RestController
@RequestMapping("/yusuan/shangniannz")
@Slf4j
public class CaiwuShangnianNzController extends JeecgController<CaiwuShangnianNz, ICaiwuShangnianNzService> {
   @Autowired
   private ICaiwuShangnianNzService caiwuShangnianService;
   @Autowired
   private ISysDepartService sysDepartService;

   @PostMapping("/addlist")
   public Result<?> addList(@RequestBody List<CaiwuShangnianNz> list){
       this.caiwuShangnianService.saveOrUpdateBatch(list);
       return Result.ok("操作成功");
   }

    /**
     * 加载所有数据
     */
    @RequestMapping(value = "/loadData", method = RequestMethod.GET)
    public Result<List<CaiwuShangnianNz>> loadTreeRoot(@RequestParam( value = "deptId",required = false)String deptId,@RequestParam(name="pid") String pid) {
        if(StringUtils.isBlank(deptId)){
            String orgCode = ((LoginUser) SecurityUtils.getSubject().getPrincipal()).getOrgCode();
            deptId = this.sysDepartService.getOne(new LambdaQueryWrapper<SysDepart>().eq(SysDepart::getOrgCode,orgCode)).getId();
        }
        Result<List<CaiwuShangnianNz>> result = new Result<List<CaiwuShangnianNz>>();
        try {
            List<CaiwuShangnianNz> ls = this.caiwuShangnianService.listData(deptId,pid);
            loadDataChildren(deptId,ls);
            result.setResult(ls);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage(e.getMessage());
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * 递归求子节点 同步加载用到
     */
    private void loadDataChildren(String deptId,List<CaiwuShangnianNz> ls) {
        for (CaiwuShangnianNz tsm : ls) {
            List<CaiwuShangnianNz> temp = this.caiwuShangnianService.listData(deptId,tsm.getTreeId());
            if(temp!=null && temp.size()>0) {
                tsm.setChildren(temp);
                loadDataChildren(deptId,temp);
            }
        }
    }
}
